package 爆刷leetcode.day0614;

/**
 * @Author yaya
 * @Create 2024/6/14 20:27
 * Description:
 */
public class Code0138_CopyRandomList {

    private static class Node {
        int val;
        Node next;
        Node random;

        Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        Node temp = head;
        Node next = null;
        while (temp != null) {
            next = temp.next;
            temp.next = new Node(temp.val);
            temp.next.next = next;
            temp = next;
        }

        temp = head;
        while (temp != null) {
            next = temp.next.next;
            temp.next.random = temp.random == null ? null : temp.random.next;
            temp = next;
        }

        Node nodeC = null;
        Node res = head.next;
        temp = head;
        while (temp != null) {
            next = temp.next.next;
            nodeC = temp.next;
            temp.next = next;
            nodeC.next = next != null ? next.next : null;
            temp = next;
        }

        return res;
    }
}
